package dai.samples.metrics;

import com.codahale.metrics.Counter;
import com.codahale.metrics.MetricRegistry;

import java.util.Queue;
import java.util.Random;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * 计数器，内部使用AtomicLong提供了增加和减少值的方法，用来记录一个值的变化
 * @author daify
 * @date 2022-05-06
 */
public class CounterTest extends MetricBase{
    private static Queue<String> queue = new LinkedBlockingQueue<String>();

    private static Counter counter;

    private static Random random = new Random();

    public static void main(String[] args) throws InterruptedException {
        initMetric();

        // 注册一个counter
        counter = registry.counter(MetricRegistry.name(Queue.class,"jobs","size"));
        int num = 1;
        while(true){
            Thread.sleep(200);
            if (random.nextDouble() > 0.7){
                String job = takeJob();
                System.out.println("take job : "+ job);
            }else{
                String job = "Job-"+num;
                addJob(job);
                System.out.println("add job : "+job);
            }
            num++;
        }
    }

    private static void addJob(String job) {
        counter.inc();
        queue.offer(job);
    }

    private static String takeJob() {
        counter.dec();
        return queue.poll();
    }

}
